package com.ruoyi.form.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.MongoPage;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.form.base.Def;
import com.ruoyi.form.base.StringUtils;
import com.ruoyi.form.domain.*;
import com.ruoyi.form.service.IAxFormDataService;
import com.ruoyi.form.service.IAxFieldService;
import com.ruoyi.form.service.IDataService;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【请填写功能名称】Controller
 *
 * @author LZF
 * @date 2025-07-18
 */
@RestController
@RequestMapping("/form/data")
public class AxFormDataController extends BaseController {
    @Resource
    IAxFormDataService axFormDataService;
    @Autowired
    IAxFieldService axFieldService;
    @Autowired
    private IDataService dataService;
    /**
     * 查询检索条件&数据列表
     *
     * @param query 查询参数
     * @return {@link ProjectResult}
     * @date 2025-06-27
     * @author lzf
     */
    @GetMapping("/listpage")
    public ProjectResult getNaviDataListPage(DataQuery query) {
        ProjectResult result = new ProjectResult();
        if (StringUtils.isEmpty(query.getPjId())) {
            return result;
        }
        String configModelId = query.getPjId();
        if (StringUtils.isEmpty(configModelId)) {
            return result;
        }
        query.setPjId(configModelId);
        List<AxModelField> tableColumList = axFormDataService.queryTableColumnList(configModelId);
        List<AxModelField> filterColumList = axFormDataService.queryFilterColumnList(configModelId);
        AxField axField = new AxField();
        axField.setIsDesign("1");
        axField.setModelId(configModelId);
        FieldLayout layoutList = axFieldService.layoutList(axField);
        ProjectResult projectResult = new ProjectResult();
        projectResult.setFilterBasicList(filterColumList);
        projectResult.setColumList(tableColumList);
        projectResult.setLayoutList(layoutList);
        Map map = new HashMap();
        if (query.getFormJson() != null) {
            for (Map.Entry<String, Object> entry : query.getFormJson().entrySet()) {
                String key = entry.getKey();
                String value = (String)entry.getValue();
                System.out.println("Key: " + key + ", Value: " + value);
                if (StringUtils.isEmpty(value)) {
                    continue;
                }
                if (key.equals("pjId")) {
                    map.put(Def.TableId, value);
                    continue;
                }
                map.put(key, value);
            }
        }
        TableDataInfo tableDataInfo = axFormDataService.searchDataList(query.getPageNum(), query.getPageSize(), map);
        projectResult.setTableDataInfo(tableDataInfo);
        return projectResult;
    }
    /**
     * 根据数据id列表删除数据
     *
     * @param ids 待删除数据id列表
     * @return {@link ResponseResult}
     * @date 2025-06-27
     * @author lzf
     */
    @DeleteMapping(value = "deleteKnowLedge/{ids}")
    public ResponseResult deleteKnowLedge(@PathVariable("ids") String[] ids) {
        return axFormDataService.deleteKnowLedges(ids);
    }
    /**
     * 根据数据id查询数据详情
     *
     * @param id 数据条目id
     * @return {@link AjaxResult}
     * @date 2025-06-27
     * @author lzf
     */
    @GetMapping(value = "getKnowLedgeInfo/{id}")
    public AjaxResult getKnowLedgeInfo(@PathVariable("id") String id) {
        return AjaxResult.success(axFormDataService.getKnowLedgeInfo(id));
    }
    /**
     * 通过tplId和parentId获取全部复杂属性
     * @date 2025-06-27
     * @param tplId  模型id
     * @param parentId 复杂属性id
     * @return
     */
    @RequestMapping("/getJson")
    public MongoPage getJson(String tplId, String parentId, Integer pageNum, Integer pageSize){
        MongoPage mongoPage = new MongoPage();
        mongoPage.setPageSize(pageSize);
        mongoPage.setPageNum(pageNum);
        return dataService.findExtendUseMongo(mongoPage, Def.formSubDataCollection, tplId, parentId);
    }
    /**
     * 生成新的数据条目id
     * @date 2025-06-27
     * @return uuid
     */
    @GetMapping("/newDataId")
    public String newDataId() {
        return IdUtils.simpleUUID();
    }
    /**
     * 新增数据
     * @param map  数据对象
     * @date 2025-06-27
     * @return AjaxResult 通用结果
     */
    @PostMapping(value = "/saveKnowLedge")
    public AjaxResult saveKnowLedge(@RequestBody Document map) {
        String _id = axFormDataService.saveKnowLedgeData(map,false);
        return AjaxResult.success("保存生成", _id);
    }
    /**
     * 通过复杂属性id 获取复杂属性
     * @date 2025-06-27
     * @param dataId
     * @return
     */
    @RequestMapping("/getJsonById")
    public AjaxResult getJson(String dataId){
        Document document = this.dataService.findOneUseMongo(dataId, Def.formSubDataCollection);
        return AjaxResult.success(document);
    }
    /**
     * 复杂属性保存一个对象
     * @param tplId: 复杂属性 父属性id
     * @param parentId： 对应模型的mongoid
     * @param json
     */
    @RequestMapping(value = "/saveJson")
    @PostMapping
    public AjaxResult saveJson(@RequestParam String tplId, @RequestParam String parentId, @RequestBody Document json) {
        try {
            if (!json.containsKey(Def.sortNum)){
                json.put(Def.sortNum, dataService.findMaxSortNum(tplId,parentId)+1);
            }
            return AjaxResult.success(dataService.saveDataUseMongo(Def.formSubDataCollection, tplId, json));
        } catch (Exception e) {
        }
        return AjaxResult.error();
    }
    /**
     * 复杂属性保存一个对象
     * @param ids: 子表数据条目id列表
     */
    @DeleteMapping("/delJsonById/{ids}")
    public AjaxResult delJsonById(@PathVariable String ids){
        List<String> idList = new ArrayList<>();
        String[] id = ids.split(",");
        for(int i = 0;i < id.length;i++){
            idList.add(id[i]);
        }
        dataService.delDataUseMongo(idList, Def.formSubDataCollection);
        return AjaxResult.success("删除成功");
    }
    /**
     * 复杂属性保存一个对象
     * @param tplId: 模型id
     * @param parentId: 父级字段id
     * @param type: 上/下
     */
    @PostMapping("/editUpOrDown/{tplId}/{parentId}/{id}/{type}")
    public AjaxResult editUpOrDown(@PathVariable("tplId") String tplId, @PathVariable("parentId") String parentId, @PathVariable("id") String id, @PathVariable("type") String type){
        AjaxResult ajaxResult = new AjaxResult();
        MongoPage mongoPage = new MongoPage();
        ajaxResult = dataService.editUpOrDown(mongoPage, Def.formSubDataCollection, tplId, parentId, id, type);
        return ajaxResult;
    }
}
